From 8c5726515e447c52c26d8f0920cb5a6e7dc4547e Mon Sep 17 00:00:00 2001 From: surdeus Date: Fri, 1 Mar 2024 01:19:07 +0500 Subject: [PATCH] feat: betterified the contents.Type and context way to set content type. --- contents/main.go | 24 ++++++++++++++---------- context.go | 30 ++++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 14 deletions(-) diff --git a/contents/main.go b/contents/main.go index 7c9e53c..e550f2e 100644 --- a/contents/main.go +++ b/contents/main.go @@ -1,25 +1,29 @@ package contents -import ( -) +type Option interface { + KeyValue() [2]string +} type CharSet string const ( Utf8 = "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) -} diff --git a/context.go b/context.go index 6ca1fff..720625d 100644 --- a/context.go +++ b/context.go @@ -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...) }