A
A
Alexander Saneev2017-03-26 15:50:47
go
Alexander Saneev, 2017-03-26 15:50:47

How to implement CNC in Golang?

How to implement a human-readable url in Golang?
How to catch the url and parse it into parts?
Post a code example please.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2017-03-26
@pav5000

On the gin framework, for example, it would look like this:

package main

import (
  "net/http"

  "gopkg.in/gin-gonic/gin.v1"
)

func main() {
  r := gin.Default()
  r.GET("/ping", PingHandler)
  r.GET("/user/:name", UserGetHandler)
  r.POST("/user/:name", UserPostHandler)
  r.Run()
}

func PingHandler(c *gin.Context) {
  c.JSON(200, gin.H{
    "message": "pong",
  })
}

func UserGetHandler(c *gin.Context) {
  name := c.Param("name")
  c.String(http.StatusOK, "Hello %s\n", name)
}

func UserPostHandler(c *gin.Context) {
  name := c.Param("name")
  // Do some actions
  c.String(http.StatusOK, "User %s was edited\n", name)
}

$ curl 127.0.0.1:8080/ping
{"message":"pong"}
$ curl 127.0.0.1:8080/user/john
Hello john
$ curl -XPOST 127.0.0.1:8080/user/john
User john was edited

K
kolo2012, 2017-03-28
@kolo2012

https://github.com/julienschmidt/httprouter

package main

import (
    "fmt"
    "github.com/julienschmidt/httprouter"
    "net/http"
    "log"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func main() {
    router := httprouter.New()
    router.GET("/", Index)
    router.GET("/hello/:name", Hello)

    log.Fatal(http.ListenAndServe(":8080", router))
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question