1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- package srv
- import (
- "fmt"
- "net/http"
- "time"
- )
- type Res struct {
- w http.ResponseWriter
- r *http.Request
- status int
- cookies map[string]*http.Cookie
- }
- func (res *Res) Construct(w http.ResponseWriter, r *http.Request) {
- res.w = w
- res.r = r
- res.status = 200
- res.cookies = make(map[string]*http.Cookie)
- }
- func (res *Res) Send(txt string) {
- for _, v := range res.cookies {
- http.SetCookie(res.w, v)
- }
- res.w.WriteHeader(res.status)
- fmt.Fprint(res.w, txt)
- }
- func (res *Res) File(filePath string) {
- http.ServeFile(res.w, res.r, filePath)
- // file, err := os.Open(filePath)
- // if err != nil {
- // utils.Err(err)
- // return err
- // }
- // defer file.Close()
- // _, err = io.Copy(res.w, file)
- // if err != nil {
- // utils.Err(err)
- // return err
- // }
- // return nil
- }
- func (res *Res) Redirect(url string) {
- for _, v := range res.cookies {
- http.SetCookie(res.w, v)
- }
- http.Redirect(res.w, res.r, url, http.StatusTemporaryRedirect)
- }
- func (res *Res) Status(code int) *Res {
- res.status = code
- return res
- }
- func (res *Res) Header(k string, v string) *Res {
- res.w.Header().Add(k, v)
- return res
- }
- func (res *Res) JSON(json string) {
- res.Header("Content-type", "application/json").Send(json)
- }
- func (res *Res) Cookie(name string, val string, expires ...time.Time) *Res {
- Expires := time.Now().Add(365 * 24 * time.Hour)
- for _, v := range expires {
- Expires = v
- }
- cookie := &http.Cookie{
- Name: name,
- Value: val,
- Expires: Expires,
- Path: "/",
- Secure: false,
- HttpOnly: true,
- SameSite: http.SameSiteStrictMode,
- }
- res.cookies[name] = cookie
- return res
- }
|