Golang uses the http module to construct the redis read/write query api

Source: Internet
Author: User
Cutting-edge: golang has been used for some high-performance APIs over the past two days and does not want to put pressure on the platform interfaces. The platform has to perform a lot of time-consuming operations, and uwsgi may encounter a few errors. After finding a circle, you do not know how to solve the problem. Take a detour for the moment, and use a simple interface for testing. Slowly migrate complicated operations to golang. Words

Cutting-edge: golang has been used for some high-performance APIs over the past two days and does not want to put pressure on the platform interfaces. The platform has to perform a lot of time-consuming operations, and uwsgi may encounter a few errors. After finding a circle, you do not know how to solve the problem. Take a detour for the moment, and use a simple interface for testing. Slowly migrate complicated operations to golang. Words

Frontier:

In the past two days, I tried to use golang for some high-performance APIs and didn't want to aggregate the pressure on the platform interfaces. The platform has to perform a lot of time-consuming operations, and uwsgi may encounter a few errors. After finding a circle, you do not know how to solve the problem. Take a detour for the moment, and use a simple interface for testing. Slowly migrate complicated operations to golang.

Speaking of the previous High-Performance interfaces, the most widely used solution is the combination of nginx lua, which is super powerful. You can refer to the nginx lua article I wrote earlier. I am only reading golang during this time. I will try to use golang to implement the redis api. I will give you a simple try.

Start with golang's redis Module

cd $GOPATH/srcgit clone git://github.com/alphazero/Go-Redis.git rediscd redisgo install

A simple example of golang's operation on redis

//xiaorui.ccpackage mainimport (    "os";    "bufio";    "log";    "fmt";    "redis";)/*    hello world, redis style.*/func main () {    // create the client.  Here we are using a synchronous client.    // Using the default ConnectionSpec, we are specifying the client to connect    // to db 13 (e.g. SELECT 13), and a password of go-redis (e.g. AUTH go-redis)    spec := redis.DefaultSpec().Db(13).Password("go-redis");    client, e := redis.NewSynchClientWithSpec (spec);    if e != nil { log.Println ("failed to create the client", e); return }    key := "examples/hello/user.name";    value, e := client.Get(key);    if e!= nil { log.Println ("error on Get", e); return }    if value == nil {        fmt.Printf("\nHello, don't believe we've met before!\nYour name? ");        reader:= bufio.NewReader(os.Stdin);        user, _ := reader.ReadString(byte('\n'));        if len(user) > 1 {            user = user[0:len(user)-1];            value = []byte(user);            client.Set(key, value);        } else {            fmt.Printf ("vafanculo!\n");            return;        }    }    fmt.Printf ("Hey, ciao %s!\n", fmt.Sprintf("%s", value));}

After reading the examples I have written, you can make more extensions.


In fact, golang's built-in http is very mvc, and the three have made some separation, like web. py tornado in python...

Test results:

Server startup

Client Testing

// Xiaorui. ccpackage mainimport ("fmt" "net/http" "io/ioutil" "log" "time" "redis") // xiaorui. ccconst AddForm = 'name: Age: 'const setform = 'key: value: 'func Handler (w http. responseWriter, r * http. request) {path: = r. URL. path [1:] if path = "favicon. ico "{http. notFound (w, r) return} if path = "" {path = "index.html"} contents, err: = ioutil. readFile (path) if err! = Nil {fmt. fprintf (w, "404") return} fmt. fprintf (w, "% s \ n", contents)} func Add (w http. responseWriter, r * http. request) {name: = r. formValue ("name") age: = r. formValue ("age") if name = "" | age = "" {fmt. fprint (w, AddForm) return} fmt. fprintf (w, "Save: Your name is % s, You age is % s", name, age)} func redisset (w http. responseWriter, r * http. request) {key: = r. formValue ("key") value: = r. formV Alue ("value") if key = "" | value = "" {fmt. fprint (w, setform) return} spec: = redis. defaultSpec (). db (0 ). password (""); client, e: = redis. newSynchClientWithSpec (spec); if e! = Nil {log. println ("server connection exception", e); return} inva: = [] byte (value) client. set (key, inva); fmt. fprintf (w, "Dude, the key % s and value % s you entered have been inserted into redis", key, key)} func redisget (w http. responseWriter, r * http. request) {key: = r. formValue ("key") if key = "" {fmt. fprint (w, setform) return} spec: = redis. defaultSpec (). db (0 ). password (""); client, e: = redis. newSynchClientWithSpec (spec); if e! = Nil {log. println ("server connection exception", e); return} value, e: = client. get (key); fmt. fprintf (w, "buddy, key % s and value % s", key, value)} func valueget (w http. responseWriter, r * http. request) {params: = r. URL. query () user: = params. get ("user") fmt. fprintf (w, "you are get user % s", user)} func main () {http. handleFunc ("/", Handler) http. handleFunc ("/add", Add) http. handleFunc ("/redisset", redisset) http. handleFunc ("/redisget", redisget) http. handleFunc ("/valueget", valueget) s: = & http. server {Addr: ": 80", ReadTimeout: 30 * time. second, WriteTimeout: 30 * time. second, MaxHeaderBytes: 1 <20,} log. fatal (s. listenAndServe ())}






Original article address: golang used the http module to construct the redis read/write query api. Thanks to the original author for sharing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.