feat: betterified the contents.Type and context way to set content type.

This commit is contained in:
Andrey Parhomenko 2024-03-01 01:19:07 +05:00
parent 966c1204d7
commit 801cf0d0d0
4 changed files with 46 additions and 16 deletions

View file

@ -30,7 +30,7 @@ Case(
c.Printf("Привет, Мир!")
}),
).Default(bond.Func(func(c *bond.Context){
c.SetContentType(contents.Plain)
c.SetContentType(contents.Plain, contents.Utf8)
c.Printf(
"AbsPath: %q\n" +
"Prefix: %q\n" +

View file

@ -1,25 +1,29 @@
package contents
import (
)
type Option interface {
KeyValue() [2]string
}
type CharSet string
const (
Utf8 = "utf-8"
Utf8 CharSet = "utf-8"
)
func (cs CharSet) KeyValue() [2]string {
return [2]string{
"charset",
string(cs),
}
}
type Type string
const (
// Using the UTF-8 by default.
Unknown Type = "application/octet-stream"
Binary
Plain Type = "text/plain"
Css Type = "text/css"
Html Type = "text/html"
Json Type = "application/json"
UrlEncoded = "application/x-www-form-urlencoded"
Plain= "text/plain"
Css= "text/css"
Html= "text/html"
Json= "application/json"
UrlEncoded= "application/x-www-form-urlencoded"
)
func (t Type) CharSet(set CharSet) Type {
return t + ";" + Type(set)
}

View file

@ -2,6 +2,7 @@ package bond
import (
"io"
"strings"
"encoding/json"
"net/http"
"net/url"
@ -31,12 +32,17 @@ func (c *Context) SetStatus(status Status) {
}
// Set the reply content type.
func (c *Context) SetContentType(typ contents.Type) {
c.SetHeader("Content-Type", string(typ))
func (c *Context) SetContentType(typ contents.Type, opts ...contents.Option) {
ret := string(typ)
for _, opt := range opts {
kv := opt.KeyValue()
ret += ";"+kv[0]+"="+kv[1]
}
c.SetHeader("Content-Type", ret)
}
// Get the request content type.
func (c *Context) ContentType() ContentType {
func (c *Context) ContentType() contents.Type {
ret, ok := c.Header("Content-Type")
if !ok {
return ""
@ -44,7 +50,11 @@ func (c *Context) ContentType() ContentType {
if len(ret) < 1 {
return ""
}
return contents.Type(ret[0])
splits := strings.SplitN(ret[0], ";", 2)
if len(splits) < 0 {
return ""
}
return contents.Type(splits[0])
}
func (c *Context) SetHeader(k, v string) {
@ -114,6 +124,18 @@ func (c *Context) NotFound() {
http.NotFound(c.W, c.R)
}
func (c *Context) InternalServerError(err error) {
c.W.WriteHeader(http.StatusInternalServerError)
if err != nil {
c.Printf("500 Internal Server Error: %q", err)
} else {
}
}
func (c *Context) Print(v ...any) (int, error) {
return fmt.Print(v...)
}
func (c *Context) Printf(format string, v ...any) (int, error) {
return fmt.Fprintf(c.W, format, v...)
}

View file

@ -27,3 +27,7 @@ func (router *RootRouter) ServeHTTP(w ResponseWriter, r *Request) {
ctx.RelUrl = &u
router.handler.Handle(&ctx)
}
func (router *RootRouter) Handle(c *Context) {
router.handler.Handle(c)
}