使用golang的http模块构建redis读写查api

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介:

前沿:

       这两天试着用golang做一些高性能的api,不想把压力到聚合在平台的接口上。平台因为要做很多耗时间的操作,uwsgi下会出现少许错误,找了一圈不知道如何解决该问题。 暂时先绕道而行,先拿简单的接口来做测试,慢慢的把复杂的操作也迁移到golang上。

         话说以前高性能的接口,我用的最多的方案还是nginx lua的组合,超强,大家可以看看我以前写的nginx lua的文章,各方面没得说。只是这段时间正在看golang 的,就试着用golang实现redis的api,先来个简单的试试手。


里面引用的是golang自带的http模块,redis是自己down的。

golang redis的配置方法:

1
2
3
4
cd $GOPATH/src
git clone git: //github.com/alphazero/Go-Redis.git redis
cd redis
go install


先简单说下,golang对于redis的操作方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//xiaorui.cc
package main
import (
"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));
}


我写的实例,大家看懂了后,完全可以做更多的扩展。


其实golang自带的http很有mvc的感觉,三者做了一些分离,很像python里面的web.py tornado。。。


测试结果:

服务端的启动

wKioL1Mrmi3Qj3nVAAHGNMEWAPA108.jpg

客户端的测试

wKiom1MrmkSg8_TGAATqDvHKzoA311.jpg


原文:http://rfyiamcool.blog.51cto.com/1030776/1380754


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//xiaorui.cc
package main
import (
"fmt"
"net/http"
"io/ioutil"
"log"
"time"
"redis"
)
//xiaorui.cc
const AddForm = `
<html><body>
<form method= "POST" action= "/add" >
Name: <input type= "text" name= "name" >
Age: <input type= "text" name= "age" >
<input type= "submit" value= "Add" >
</form>
</body></html>
`
const setform = `
<html><body>
<form method= "POST" action= "/set" >
key: <input type= "text" name= "key" >
value: <input type= "text" name= "value" >
<input type= "submit" value= "set" >
</form>
</body></html>
`
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.FormValue( "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 ( "服务器连接有异常" , e);  return }
inva := []byte(value)
client.Set(key, inva);
fmt.Fprintf(w,  "哥们,你输入的key  %s 和value  %s 已经插入到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 ( "服务器连接有异常" , e);  return }
value, e := client.Get(key);
fmt.Fprintf(w,  "哥们,你要查询的key  %s 和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())
}


对于go的基础教程,我也写过其他的文章,大家可以参考下。










本文转自 ponpon_ 51CTO博客,原文链接:http://blog.51cto.com/liuxp0827/1387369,如需转载请自行联系原作者
目录
相关文章
|
27天前
|
JSON 监控 API
掌握使用 requests 库发送各种 HTTP 请求和处理 API 响应
本课程全面讲解了使用 Python 的 requests 库进行 API 请求与响应处理,内容涵盖环境搭建、GET 与 POST 请求、参数传递、错误处理、请求头设置及实战项目开发。通过实例教学,学员可掌握基础到高级技巧,并完成天气查询应用等实际项目,适合初学者快速上手网络编程与 API 调用。
328 130
|
2月前
|
XML JSON API
识别这些API接口定义(http,https,api,RPC,webservice,Restful api ,OpenAPI)
本内容介绍了API相关的术语分类,包括传输协议(HTTP/HTTPS)、接口风格(RESTful、WebService、RPC)及开放程度(API、OpenAPI),帮助理解各类API的特点与应用场景。
|
4月前
|
JSON 中间件 Go
Go 网络编程:HTTP服务与客户端开发
Go 语言的 `net/http` 包功能强大,可快速构建高并发 HTTP 服务。本文从创建简单 HTTP 服务入手,逐步讲解请求与响应对象、URL 参数处理、自定义路由、JSON 接口、静态文件服务、中间件编写及 HTTPS 配置等内容。通过示例代码展示如何使用 `http.HandleFunc`、`http.ServeMux`、`http.Client` 等工具实现常见功能,帮助开发者掌握构建高效 Web 应用的核心技能。
253 61
|
2月前
|
数据采集 JSON Go
Go语言实战案例:实现HTTP客户端请求并解析响应
本文是 Go 网络与并发实战系列的第 2 篇,详细介绍如何使用 Go 构建 HTTP 客户端,涵盖请求发送、响应解析、错误处理、Header 与 Body 提取等流程,并通过实战代码演示如何并发请求多个 URL,适合希望掌握 Go 网络编程基础的开发者。
|
3月前
|
JSON 前端开发 Go
Go语言实战:创建一个简单的 HTTP 服务器
本篇是《Go语言101实战》系列之一,讲解如何使用Go构建基础HTTP服务器。涵盖Go语言并发优势、HTTP服务搭建、路由处理、日志记录及测试方法,助你掌握高性能Web服务开发核心技能。
|
3月前
|
SQL 缓存 监控
SqlRest让SQL秒变Http API,还支持20+数据库(含国产数据库)
杭州奥零数据科技有限公司成立于2023年,专注于数据中台业务,维护开源项目AllData并提供商业版解决方案。AllData提供数据集成、存储、开发、治理及BI展示等一站式服务,支持AI大模型应用,助力企业高效利用数据价值。
|
3月前
|
Go
如何在Go语言的HTTP请求中设置使用代理服务器
当使用特定的代理时,在某些情况下可能需要认证信息,认证信息可以在代理URL中提供,格式通常是:
270 0
|
4月前
|
JSON 编解码 API
Go语言网络编程:使用 net/http 构建 RESTful API
本章介绍如何使用 Go 语言的 `net/http` 标准库构建 RESTful API。内容涵盖 RESTful API 的基本概念及规范,包括 GET、POST、PUT 和 DELETE 方法的实现。通过定义用户数据结构和模拟数据库,逐步实现获取用户列表、创建用户、更新用户、删除用户的 HTTP 路由处理函数。同时提供辅助函数用于路径参数解析,并展示如何设置路由器启动服务。最后通过 curl 或 Postman 测试接口功能。章节总结了路由分发、JSON 编解码、方法区分、并发安全管理和路径参数解析等关键点,为更复杂需求推荐第三方框架如 Gin、Echo 和 Chi。
|
6月前
|
中间件 Go
Golang | Gin:net/http与Gin启动web服务的简单比较
总的来说,`net/http`和 `Gin`都是优秀的库,它们各有优缺点。你应该根据你的需求和经验来选择最适合你的工具。希望这个比较可以帮助你做出决策。
227 35
|
11月前
|
网络协议 安全 Go
Go语言进行网络编程可以通过**使用TCP/IP协议栈、并发模型、HTTP协议等**方式
【10月更文挑战第28天】Go语言进行网络编程可以通过**使用TCP/IP协议栈、并发模型、HTTP协议等**方式
196 13

热门文章

最新文章