github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/web/examples/cookie.go (about)

     1  // Copyright 2014 <chaishushan{AT}gmail.com>. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // +build ingore
     6  
     7  package main
     8  
     9  import (
    10  	"fmt"
    11  	"html"
    12  
    13  	"github.com/chai2010/gopkg/web"
    14  )
    15  
    16  var cookieName = "cookie"
    17  
    18  var notice = `
    19  <div>%v</div>
    20  `
    21  var form = `
    22  <form method="POST" action="update">
    23  	<div class="field">
    24  		<label for="cookie"> Set a cookie: </label>
    25  		<input id="cookie" name="cookie"> </input>
    26  	</div>
    27  
    28  	<input type="submit" value="Submit"></input>
    29  	<input type="submit" name="submit" value="Delete"></input>
    30  </form>
    31  `
    32  
    33  func index(ctx *web.Context) string {
    34  	cookie, _ := ctx.Request.Cookie(cookieName)
    35  	var top string
    36  	if cookie == nil {
    37  		top = fmt.Sprintf(notice, "The cookie has not been set")
    38  	} else {
    39  		var val = html.EscapeString(cookie.Value)
    40  		top = fmt.Sprintf(notice, "The value of the cookie is '"+val+"'.")
    41  	}
    42  	return top + form
    43  }
    44  
    45  func update(ctx *web.Context) {
    46  	if ctx.Params["submit"] == "Delete" {
    47  		ctx.SetCookie(web.NewCookie(cookieName, "", -1))
    48  	} else {
    49  		ctx.SetCookie(web.NewCookie(cookieName, ctx.Params["cookie"], 0))
    50  	}
    51  	ctx.Redirect(301, "/")
    52  }
    53  
    54  func main() {
    55  	web.Get("/", index)
    56  	web.Post("/update", update)
    57  	web.Run("0.0.0.0:9999")
    58  }