codewars

package module
v0.0.0-...-505f4f3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 13, 2016 License: MIT Imports: 10 Imported by: 0

README

go-codewars

Build Status Go Report Card GoDoc

A Codewars API client for Go.

Example

token := "some-api-token"
cw := codewars.NewClient(token)

slug := "printing-array-elements-with-comma-delimiters"
kata, _, err := cw.Katas.GetKata(slug)
if err != nil {
    fmt.Printf("Error: %v\n\n", err)
} else {
    kataJSON, _ := json.MarshalIndent(kata, "", "  ")
    fmt.Printf("Kata:\n%s\n\n", kataJSON)
}

See more complex examples in examples folder.

Documentation

Codewars API documentation.

Documentation

Overview

Package codewars implements the client for Codewars API.

As a simple example:

token := "some-api-token"
cw := codewars.NewClient(token)

slug := "printing-array-elements-with-comma-delimiters"
kata, _, err := cw.Katas.GetKata(slug)
if err != nil {
    fmt.Printf("Error: %v\n\n", err)
} else {
    kataJSON, _ := json.MarshalIndent(kata, "", "  ")
    fmt.Printf("Kata:\n%s\n\n", kataJSON)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckResponse

func CheckResponse(res *http.Response) error

CheckResponse checks the Codewars API response for errors and returns them if present. A response is considered an error if it has a status code outside the 200 range.

Types

type AttemptSolutionOptions

type AttemptSolutionOptions struct {
	// The code that you is being submitted
	Code string `url:"code"`

	// The output format to be used.
	// (Optional)
	OutputFormat OutputFormat `url:"output_format,omitempty"`
}

AttemptSolutionOptions represents the available AttemptSolution() options.

type Client

type Client struct {

	// User agent used when communicating with the Codewars API.
	UserAgent string

	// Services used for talking to different parts of the Codewars API.
	Users    *UsersService
	Katas    *KatasService
	Deferred *DeferredService
	// contains filtered or unexported fields
}

Client represents a Codewars API client.

func NewClient

func NewClient(token string) *Client

NewClient returns a new Codewars API client.

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error)

Do executes the HTTP request and returns the response.

func (*Client) NewRequest

func (c *Client) NewRequest(method, path string, opts interface{}) (*http.Request, error)

NewRequest returns an API request.

type DeferredResponse

type DeferredResponse struct {
	Success  bool     `json:"success"`
	DMID     string   `json:"dmid"`
	Valid    bool     `json:"valid"`
	Reason   string   `json:"reason"`
	Output   []string `json:"output"`
	WallTime int      `json:"wall_time"`
}

DeferredResponse represents a Codewars deferred response.

type DeferredService

type DeferredService struct {
	// contains filtered or unexported fields
}

DeferredService handles communication with the deferred related methos of Codewars API.

func (*DeferredService) GetDeferredResponse

func (s *DeferredService) GetDeferredResponse(DMID string) (*DeferredResponse, *http.Response, error)

GetDeferredResponse is used for polling for a deferred response. This is to be used in conjunction with the attempt endpoint.

Polling should not be performed more than twice a second. If a API consumer abuses the rate guidelines, its IP address will be temporarily suspended.

type ErrorResponse

type ErrorResponse struct {
	Response *http.Response
	Success  bool   `json:"success"`
	Reason   string `json:"reason"`
}

ErrorResponse represents a Codewars API error.

func (*ErrorResponse) Error

func (er *ErrorResponse) Error() string

type Kata

type Kata struct {
	ID          string     `json:"id"`
	Name        string     `json:"name"`
	Slg         string     `json:"slug"`
	Category    string     `json:"category"`
	PublishedAt *time.Time `json:"publishedAt"`
	ApprovedAt  *time.Time `json:"approvedAt"`
	Languages   []string   `json:"languages"`
	URL         string     `json:"url"`
	Rank        struct {
		ID    int    `json:"id"`
		Name  string `json:"name"`
		Color string `json:"color"`
	} `json:"rank"`
	CreatedAt          *time.Time    `json:"createdAt"`
	CreatedBy          *KataUserData `json:"createdBy"`
	ApprovedBy         *KataUserData `json:"approvedBy"`
	Description        string        `json:"description"`
	TotalAttempts      int           `json:"totalAttempts"`
	TotalCompleted     int           `json:"totalCompleted"`
	TotalStars         int           `json:"totalStars"`
	VoteScore          int           `json:"voteScore"`
	Tags               []string      `json:"tags"`
	ContributorsWanted bool          `json:"contributorsWanted"`
	Unresolved         struct {
		Issues      int `json:"issues"`
		Suggestions int `json:"suggestions"`
	} `json:"unresolved"`
}

Kata represents a Codewars code challenge (kata).

type KataUserData

type KataUserData struct {
	Username string `json:"username"`
	URL      string `json:"url"`
}

KataUserData represents user info inside kata structure.

type KatasService

type KatasService struct {
	// contains filtered or unexported fields
}

KatasService handles communication with the code challenges (katas) related methos of Codewars API.

func (*KatasService) AttemptSolution

func (s *KatasService) AttemptSolution(projectID, solutionID string, opts *AttemptSolutionOptions) (*SolutionAttemptResponse, *http.Response, error)

AttemptSolution is used to submit a solution to be validated by the code challenge author’s test cases. It will return a deferred message id (dmid) which will be used to poll for the response. Polling must be used to retrieve the response.

func (*KatasService) FinalizeSolution

func (s *KatasService) FinalizeSolution(projectID, solutionID string) (*SolutionResponse, *http.Response, error)

FinalizeSolution is used to finalize the previously submitted solution. This endpoint will only return a success message if there has been a previously successful solution.

func (*KatasService) GetKata

func (s *KatasService) GetKata(slug string) (*Kata, *http.Response, error)

GetKata gets a single code challenge (kata).

func (*KatasService) Train

func (s *KatasService) Train(slug, lang string) (*TrainingSession, *http.Response, error)

Train begins a new training session for the specified code challenge (kata).

If the code challenge has not been started by yet by the user, then a timer will begin as soon as the request is made. The timer is used solely for tracking average completion times and does not affect the user’s honor in any way.

func (*KatasService) TrainNext

func (s *KatasService) TrainNext(lang string, opts *TrainNextOptions) (*TrainingSession, *http.Response, error)

TrainNext begins a new training session for the next code challenge (kata) within user's training queue.

If the next code challenge within your queue is one that you have not started yet, then a timer will begin as soon as the request is made. The timer is used solely for tracking average completion times and does not affect your honor in any way.

type OutputFormat

type OutputFormat string

OutputFormat is the output format to be used by AttemptSolution().

const (
	// OutputFormatHTML is a HTML format.
	OutputFormatHTML OutputFormat = "html"

	// OutputFormatRaw is a raw format.
	OutputFormatRaw OutputFormat = "raw"
)

type Session

type Session struct {
	// This ID value will be needed when submitting a solution.
	ProjectID string
	// This ID value will be needed when submitting a solution.
	SolutionID string
	// This is the initial solution code that is given to a user.
	Setup string
	// This is the example test cases that are initially given to a user.
	ExampleFixture string
	// If the user is continuing a previous started solution,
	// this value will represent their previous work.
	Code string
}

Session represents Codewars API Session.

type SolutionAttemptResponse

type SolutionAttemptResponse struct {
	SolutionResponse
	DMID string
}

SolutionAttemptResponse represents the Codewars API response on solution attempt, which contains a deferred message id (dmid) which will be used to poll for the response.

type SolutionResponse

type SolutionResponse struct {
	Success bool
}

SolutionResponse represents the Codewars API response on solution POSTing.

type StrategyType

type StrategyType string

StrategyType represents a value for selecting a code challenge selection strategy.

All strategies will prefer incomplete and non-started code challenges, unless otherwise stated.

const (
	// StrategyDefault also referred to as the “Rank Up” workout.
	// Will select a challenge that is above your current level.
	StrategyDefault StrategyType = "default"

	// StrategyRandom randomly selected code challenges.
	StrategyRandom StrategyType = "random"

	// StrategyReferenceWorkout will select code challenges
	// that are tagged as reference.
	StrategyReferenceWorkout StrategyType = "reference_workout"

	// StrategyBetaWorkout will select beta code challenges.
	StrategyBetaWorkout StrategyType = "beta_workout"

	// StrategyRetrainWorkout will focus on code challenges
	// that you have already completed.
	StrategyRetrainWorkout StrategyType = "retrain_workout"

	// StrategyAlgorithmRetest will focus on algorithm code challenges
	// that you have already completed.
	StrategyAlgorithmRetest StrategyType = "algorithm_retest"

	// StrategyKyu8Workout will focus on 8 kyu code challenges.
	StrategyKyu8Workout StrategyType = "kyu_8_workout"

	// StrategyKyu7Workout will focus on 7 kyu code challenges.
	StrategyKyu7Workout StrategyType = "kyu_7_workout"

	// StrategyKyu6Workout will focus on 6 kyu code challenges.
	StrategyKyu6Workout StrategyType = "kyu_6_workout"

	// StrategyKyu5Workout will focus on 5 kyu code challenges.
	StrategyKyu5Workout StrategyType = "kyu_5_workout"

	// StrategyKyu4Workout will focus on 4 kyu code challenges.
	StrategyKyu4Workout StrategyType = "kyu_4_workout"

	// StrategyKyu3Workout will focus on 3 kyu code challenges.
	StrategyKyu3Workout StrategyType = "kyu_3_workout"

	// StrategyKyu2Workout will focus on 2 kyu code challenges.
	StrategyKyu2Workout StrategyType = "kyu_2_workout"

	// StrategyKyu1Workout will focus on 1 kyu code challenges.
	StrategyKyu1Workout StrategyType = "kyu_1_workout"
)

type TrainNextOptions

type TrainNextOptions struct {
	// The strategy to use for choosing what the next code challenge should be.
	// (Optional)
	Strategy StrategyType `url:"strategy,omitempty"`

	// True if you only want to peek at the next item in your queue,
	// without removing it from the queue or beginning a new training session.
	// (Optional)
	Peek bool `url:"peek,omitempty"`
}

TrainNextOptions represents the available TrainNext() options.

type TrainingSession

type TrainingSession struct {
	Name string
	Slug string

	// The code challenge description is given in markdown format.
	Description string

	Author            string
	Rank              int
	AverageCompletion float64
	Tags              []string
	Session           *Session
}

TrainingSession represents Codewars API Training Session, which includes Kata information and Session data.

type User

type User struct {
	Username            string   `json:"username"`
	Name                string   `json:"name"`
	Honor               int      `json:"honor"`
	Clan                string   `json:"clan"`
	LeaderboardPosition int      `json:"leaderboardPosition"`
	Skills              []string `json:"skills"`
	Ranks               struct {
		Overall   *UserRank            `json:"overall"`
		Languages map[string]*UserRank `json:"languages"`
	} `json:"ranks"`
	CodeChallenges struct {
		TotalAuthored  int `json:"totalAuthored"`
		TotalCompleted int `json:"totalCompleted"`
	} `json:"codeChallenges"`
}

User represents a Codewars user.

type UserRank

type UserRank struct {
	Rank  int    `json:"rank"`
	Name  string `json:"name"`
	Color string `json:"color"`
	Score int    `json:"score"`
}

UserRank represents user's overall ranking or his ranking in a particular language.

type UsersService

type UsersService struct {
	// contains filtered or unexported fields
}

UsersService handles communication with the user related methos of Codewars API.

func (*UsersService) GetUser

func (s *UsersService) GetUser(username string) (*User, *http.Response, error)

GetUser gets a single user.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL