Simple Web API Server in Golang (1)
To be an better Gopher, get your hands dirty. Topcoder offered a serials of challenges for learning Golang.
In this blog, I tried to implement "Go Learning Challenge - Simple Web-API Server"[1].
What's used in this challenge ? Following aspects and packages will be covered in this challenge
- How to create a HTTP server: net/http
- How to create routers (handlers for different URLs): regex + url
- How to write HTTP responses: net/http
- How to load JSON config: json + io/ioutil
- How to parse URL query string: url
- How to encode data in sha256/base64: sha256/base64 + strings
- How to write tests in Golang: testing
- How to parse command line arguments: flag
- How to log: log
Configuration File example:
[
{
"domain": "topcoder.com",
"users": [
{
"username": "takumi",
"password": "ilovego"
},
{
"username": "teru",
"password": "ilovejava"
},
{
"username": "toshi",
"password": "iloveapex"
}
]
},
{
"domain": "appirio.com",
"users": [
{
"username": "jun",
"password": "ilovetopcoder"
},
{
"username": "narinder",
"password": "ilovesamurai"
},
{
"username": "chris",
"password": "ilovesushi"
}
]
}
]
config.go
package SimpleWebAPIServer import (
"io/ioutil"
"encoding/json"
"errors"
) type User struct {
UserName string `json:"username"`
Password string `json:"password"`
} type Domain struct {
Name string `json:"domain"`
Users UserList `json:"users"`
} type DomainWarehouse []Domain
type UserList []User func ReadConfig(fn string) (DomainWarehouse, error) {
data, err := ioutil.ReadFile(fn)
if err != nil {
return nil, err
}
//fmt.Println(string(data)) var m DomainWarehouse
json.Unmarshal(data, &m)
return m, nil
} func (dw DomainWarehouse) GetDomain(name string) (*Domain, error) {
for _, domain := range dw {
if domain.Name == name {
return &domain, nil
}
}
return nil, errors.New("Failed to find domain")
} func (ul UserList) GetUser(username string) (*User, error) {
for _, user := range ul {
if user.UserName == username {
return &user, nil
}
}
return nil, errors.New("Failed to find user")
}
tests for config.go
package SimpleWebAPIServer import (
"testing"
"fmt"
) func TestReadConfig(t *testing.T) {
dw, err := ReadConfig("./users.json")
if err != nil {
fmt.Println(err)
t.Error("Failed to read config")
}
if dw == nil || len(dw) != {
t.Error("Failed to unmarshal json objects")
} if dw[].Name != "topcoder.com" || len(dw[].Users) != {
t.Error("Incorrect value")
}
} func TestGetDomain(t *testing.T) {
dw, err := ReadConfig("./users.json")
if err != nil {
fmt.Println(err)
t.Error("Failed to read config")
}
domain, err := dw.GetDomain("topcoder.com")
if err != nil {
fmt.Println(err)
t.Error("Failed to get domain")
}
if domain.Name != "topcoder.com" || len(domain.Users) != {
t.Error("Incorrect value")
}
} func TestGetUser(t *testing.T) {
dw, err := ReadConfig("./users.json")
if err != nil {
fmt.Println(err)
t.Error("Failed to read config")
}
domain, err := dw.GetDomain("topcoder.com")
if err != nil {
fmt.Println(err)
t.Error("Failed to get domain")
}
if domain.Name != "topcoder.com" || len(domain.Users) != {
t.Error("Incorrect value")
} ul := domain.Users
u, err := ul.GetUser("takumi")
if err != nil {
t.Error("Failed to get user")
}
if u.UserName != "takumi" || u.Password != "ilovego" {
t.Error("Invalid user values")
}
}
After implementing this simple web api server, I got better understanding of Golang syntax and Web API stuffs. For more Web API server challenges, go to [3] about OAuth2.
[1] topcoder : http://www.topcoder.com/challenge-details/30046011/?type=develop&noncache=true
[2] git : https://coding.net/u/huys03/p/SimpleWebAPIServer/git
[3] next challenge: http://www.topcoder.com/challenge-details/30046224/?type=develop
Simple Web API Server in Golang (1)的更多相关文章
- Simple Web API Server in Golang (2)
In this challenge, I tried to implement a simple OAuth2 server basing on Simple Web API Server in [1 ...
- 【ASP.NET Web API教程】2.1 创建支持CRUD操作的Web API
原文 [ASP.NET Web API教程]2.1 创建支持CRUD操作的Web API 2.1 Creating a Web API that Supports CRUD Operations2.1 ...
- 【翻译】在Visual Studio中使用Asp.Net Core MVC创建你的第一个Web API应用(一)
HTTP is not just for serving up web pages. It's also a powerful platform for building APIs that expo ...
- [转]【翻译】在Visual Studio中使用Asp.Net Core MVC创建你的第一个Web API应用(一)
本文转自:https://www.cnblogs.com/inday/p/6288707.html HTTP is not just for serving up web pages. It’s al ...
- Running Web API using Docker and Kubernetes
Context As companies are continuously seeking ways to become more Agile and embracing DevOps culture ...
- [转]Enabling CRUD Operations in ASP.NET Web API 1
本文转自:https://docs.microsoft.com/en-us/aspnet/web-api/overview/older-versions/creating-a-web-api-that ...
- Asp.Net MVC 4 Web API 中的安全认证-使用OAuth
各种语言实现的oauth认证: http://oauth.net/code/ 上一篇文章介绍了如何使用基本的http认证来实现asp.net web api的跨平台安全认证. 这里说明一个如何使用oa ...
- Creating A Simple Web Server With Golang
原文:https://tutorialedge.net/post/golang/creating-simple-web-server-with-golang/ -------------------- ...
- [转]Getting started with ASP.NET Web API OData in 3 simple steps
本文转自:https://blogs.msdn.microsoft.com/webdev/2013/01/29/getting-started-with-asp-net-web-api-odata-i ...
随机推荐
- EntityFramework异常The specified cast from a materialized 'System.Double' type to the 'System.Single' type is not valid.
实体类: public class ReportEntity { public string FactorName { get; set; } public double MaxVal { get; ...
- spring注入 属性注入 构造器注入 set方法注入
spring注入 属性注入 构造器注入 set方法注入(外部bean注入)
- 【刷题】LOJ 6006 「网络流 24 题」试题库
题目描述 假设一个试题库中有 \(n\) 道试题.每道试题都标明了所属类别.同一道题可能有多个类别属性.现要从题库中抽取 \(m\) 道题组成试卷.并要求试卷包含指定类型的试题.试设计一个满足要求的组 ...
- NOIP2018初赛提高组复习提纲(By HGOI LJC)
Download:https://pan.baidu.com/s/16khhFf_0RsUjJLETreb20w (PDF) https://pan.baidu.com/s/1BVZqLs3q1clZ ...
- 2017年8道php面试题(真题+答案)
1.<?php echo count(strlen(“http://php.net”)); ?>的执行结果是? 答案:1 .如果var是普通变量,则返回1.正常情况下返回var中的元素或属 ...
- Nginx反向代理1--基本介绍-虚拟主机
1 Nginx 1.1 什么是nginx Nginx是一款高性能的http 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器.由俄罗斯的程序设计师Igor Sysoev所开发, ...
- C++ new动态数组初始化
strlen函数是不包括‘\0’的长度的,sizeof计算的结果才包括'\0'的长度: C++ new动态数组初始化void testnew( const char* str ) { if (!str ...
- vmware:Could not open /dev/vmmon: No such file or directory.
Q: Could not open /dev/vmmon: No such file or directory. Please make sure that the kernel module `vm ...
- 【CSS】float属性
float浮动属性1.作用: 将页面元素浮动起来,使其能够向左或者向右排列 2.应用: 实现页面中布局的左右排版 实现图文环绕的版式效果 3.值: 4.原理: 浮动元素将脱离默认的文档流,漂浮在默认文 ...
- Java基础-使用Idea进行远程调试
Java基础-使用Idea进行远程调试 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.