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)的更多相关文章

  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 ...

  2. 【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 ...

  3. 【翻译】在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 ...

  4. [转]【翻译】在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 ...

  5. Running Web API using Docker and Kubernetes

    Context As companies are continuously seeking ways to become more Agile and embracing DevOps culture ...

  6. [转]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 ...

  7. Asp.Net MVC 4 Web API 中的安全认证-使用OAuth

    各种语言实现的oauth认证: http://oauth.net/code/ 上一篇文章介绍了如何使用基本的http认证来实现asp.net web api的跨平台安全认证. 这里说明一个如何使用oa ...

  8. Creating A Simple Web Server With Golang

    原文:https://tutorialedge.net/post/golang/creating-simple-web-server-with-golang/ -------------------- ...

  9. [转]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 ...

随机推荐

  1. Vue---从后台获取数据vue-resource的使用方法

    作为前端人员,在开发过程中,我们大多数情况都需要从后台请求数据,那么在vue中怎样从后台获取数据呢?接下来,我简单介绍一下vue-resource的使用方法,希望对大家有帮助. 一.下载vue-res ...

  2. Java之Map的使用场景

    总结之 Map接口 的使用场景(day04) Map: Map中的集合,元素是成对存在的(理解为夫妻).每个元素由键与值两部分组成,通过键可以找对所对应的值 Map中的集合不能包含重复的键,值可以重复 ...

  3. win10 Jmeter下载安装与使用教程

    1.下载 2.安装 下载完成后解压文件(不需要安装) 之后需要配置jmeter环境变量 1)新增新增JMETER_HOME系统变量 2)编辑CLASSPATH变量,加上%JMETER_HOME%\li ...

  4. MT【168】还是两根法

    设二次函数$f(x)=ax^2+bx+c(a>0)$,方程$f(x)=x$的两根$x_1,x_2$满足$0<x_1<x_2<\dfrac{1}{a}$,(Ⅰ)当$x\in(0, ...

  5. AtCoder Grand Contest 008

    AtCoder Grand Contest 008 A - Simple Calculator 翻译 有一个计算器,上面有一个显示按钮和两个其他的按钮.初始时,计算器上显示的数字是\(x\),现在想把 ...

  6. BZOJ 百题纪念!

    一百题辣! 现在NOI知识点中最基础的那部分已经学完了--这几天发现自己会写SA啊树剖啊可持久化Trie啊之类模板题--还挺开心的-- 逛了两天学长博客之后--BZOJ100题辣--也挺开心的-- 现 ...

  7. POJ 3259 Wormholes(最短路径,求负环)

    POJ 3259 Wormholes(最短路径,求负环) Description While exploring his many farms, Farmer John has discovered ...

  8. CodeForces 获得数据

    针对程序的输出可以看见 CodeForces :当输入.输出超过一定字符,会隐藏内容 所以:分若干个程序进行输入数据的获取 1. ;i<=q;i++) { scanf("%ld%ld% ...

  9. zabbix agent安装(三)

    转载于https://mp.weixin.qq.com/s/33ab-JLoRfMkeI4aZDciJQ 前一篇文章介绍了zabbix server安装,这篇文章主要讲解zabbix agent安装以 ...

  10. 弹指之间 -- Slow Soul

    CHAPTER 16 慢灵魂乐 Slow Soul (8Beat) Slow Soul每小节内几乎都是以8分音符弹奏,又称之为8Beat节奏,80左右的速度最能表现此节奏特色. 示例曲目: 拥抱